/* eslint-disable react/require-default-props */
/**
 * 配置职位角色中的自定义表单控件
 * select
 */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Select, Spin } from 'antd';
import { getEffectSource, everyRequire } from './utils';

const { Option } = Select;
const SelectForm = React.forwardRef(({ onChange, value, getData, params, ...rest }, ref) => {
    const { selectProps, fieldsName, requireParam } = rest;
    const { selectValue, selectTitle } = fieldsName;
    const [selectList, setSelectList] = useState([]);
    const [loading, setLoading] = useState(false);
    const fetchList = async () => {
        if (!everyRequire(params, requireParam)) return;
        setLoading(true);
        const result = await getData(params);
        setLoading(false);
        setSelectList(result || []);
    };
    useEffect(() => {
        fetchList();
    }, getEffectSource(params));
    return (
        <Spin spinning={loading}>
            <Select
                ref={ref}
                // see: https://github.com/ant-design/ant-design/issues/6543
                value={value || undefined}
                onChange={onChange}
                {...selectProps}
            >
                {selectList.map(item => (
                    <Option
                        {...item}
                        title={item[selectTitle]}
                        value={item[selectValue]}
                        key={item.id}
                        posttyperemark={item.postTypeRemark ? item.postTypeRemark : ''}
                        remark={item.remark ? item.remark : ''}
                    >
                        {item[selectTitle]}
                    </Option>
                ))}
            </Select>
        </Spin>
    );
});

SelectForm.propTypes = {
    onChange: PropTypes.func,
    /**
     * request 请求参数
     */
    params: PropTypes.object,
    /**
     * 获取数据
     */
    getData: PropTypes.func,
    /**
     * 自定义字段
     */
    fieldsName: PropTypes.object,
    // select 属性
    selectProps: PropTypes.object
};

SelectForm.defaultProps = {
    onChange: () => {},
    selectProps: {}
};

export default SelectForm;
